package com.simonall.print;

import java.io.FileNotFoundException;
import java.io.InputStream;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.Media;
import javax.print.attribute.standard.OrientationRequested;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;

import com.simonall.enums.FileExtenNameEnum;

import cn.hutool.http.HttpUtil;

/**
 * 简单打印服务，不做处理，直接打印
 * 
 * @author simonall
 */
public class SimplePdfPrintHandler implements PrintHandler {
	
	private DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;

	@Override
	public FileExtenNameEnum[] handleType() {
		return new FileExtenNameEnum[] { FileExtenNameEnum.PDF }; // 能处理类型
	}

	@Override
	public void print(InputStream input, PrintService service, Integer copies) throws Exception {
		byte[] bytes = new byte[input.available()];
		input.read(bytes);
		print(bytes, service, copies);
	}

	@Override
	public void print(byte[] bytes, PrintService service, Integer copies) throws Exception {
		Media[] objs = (Media[]) service.getSupportedAttributeValues(Media.class, null, null);
        for (Media obj : objs) {
            System.out.println("类型：" + obj.getClass().getName() + "=" + obj);
        }
		
		PDDocument document = null;
		try {
			document = PDDocument.load(bytes);
			// document.setAllSecurityToBeRemoved(true);
			PDFPageable pdfable = new PDFPageable(document);

			DocAttributeSet docas = new HashDocAttributeSet();
			docas.add(OrientationRequested.PORTRAIT);
			// docas.add(ColorSupported.SUPPORTED);
			Doc doc = new SimpleDoc(pdfable, flavor, docas);

			PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
			pras.add(new Copies(copies));
			
			DocPrintJob printJob = service.createPrintJob();
			printJob.print(doc, pras);
		} finally {
			if (document != null) {
				document.close();
			}
		}
	}

	public static void main(String[] args) throws FileNotFoundException, Exception {
		PrintHandler handler = new SimplePdfPrintHandler();

		byte[] bytes = null;
		try {
			String url = "https://asmerp.oss-cn-shenzhen.aliyuncs.com/package-labels/small-bag/2020-12-22/c50ccda73218.pdf";
			bytes = HttpUtil.downloadBytes(url);
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
		handler.print(bytes, handler.defaultService(), 1);
	}
}
